import app from 'flarum/forum/app';
import Modal from "flarum/common/components/Modal";
import ItemList from "flarum/common/utils/ItemList";
import Button from 'flarum/common/components/Button';
import Stream from 'flarum/utils/Stream';

export default class AuthMobileModal extends Modal {
  static isDismissible = true;
  oncreate(vnode) {
    super.oncreate(vnode);
    this.count = 60;
    this.mobile = Stream(this.attrs.mobile || '');
    this.code = Stream(this.attrs.code || '');
    this.sendingSms = false;
    this.liked = true;
    this.loading = false;
  }
  className() {
    // Custom CSS classes to apply to the modal
    return 'bindmobile-modal-class';
  }
  title() {
    return <p>绑定手机</p>;
  }
  content() {
    return (
      <div className="Modal-body">
        {this.form().toArray()}
      </div>
    );
  }
  form() {
    const items = new ItemList();
    items.add(
      'mobile',
      <div className="Form-group">
        <label>手机号</label>
        <input
          className="FormControl"
          placeholder="请填写手机号"
          type="number"
          bidi={this.mobile}
        />
      </div>,
      60
    )
    items.add(
      'msgcode',
      <div className="Form-group">
        <label>验证码</label>
        <view class="auth-line">
          <input
            className="FormControl msgcode"
            placeholder="请填写验证码"
            type="number"
            bidi={this.code}>

          </input>
          <button type="button" className="Button Button--primary"
            onclick={this.sendCode.bind(this)} disabled={this.sendingSms}>{
              this.liked
                ? '获取验证码'
                : `${this.count} 秒后重发`
            }</button>
        </view>
      </div>,
      60
    )
    items.add(
      'submit',
      <div className="Form-group">
        {Button.component(
          {
            className: 'Button Button--primary',
            type: 'submit',
            loading: this.loading,
          },
          '立即绑定'
        )}
      </div>,
      -10
    );
    return items;
  }
  countDown() {
    if (this.count === 1) {
      this.count = 60;
      this.liked = true;
      this.sendingSms = false;
    } else {
      this.count = this.count - 1;
      this.liked = false;
      setTimeout(this.countDown.bind(this), 1000);
    }
    m.redraw();
  }
  sendCode() {
    if (!this.liked) {
      return;
    }
    if (this.mobile() == '') {
      app.alerts.show({ type: 'error' }, "请填写手机号！");
      return;
    }
    if (!this.isMobile(this.mobile())) {
      app.alerts.show({ type: 'error' }, "手机号格式错误！");
      return;
    }
    this.sendingSms = true;
    app.request({
      method: 'POST',
      url: app.forum.attribute('apiUrl') + '/sendcode',
      body: {
        phone: this.mobile(),
        code: this.code(),
      },
      errorHandler: this.onerror.bind(this),
    })
      .then(() => {
        this.countDown();
      });
  }
  onerror(error) {
    error.alert.content = error.response;
    super.onerror(error);
    this.sendingSms = false;
    console.log('err');
  }
  isMobile(value) {
    return /^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value);
  }
  onsubmit(e) {
    e.preventDefault();
    this.loading = true;
    app
      .request({
        method: 'POST',
        url: app.forum.attribute('apiUrl') + '/smscheck',
        body: {
          phone: this.mobile(),
          code: this.code(),
        },
        errorHandler: this.onerror.bind(this),
      })
      .then(() => {
        app.modal.close()
        app.alerts.show({ type: 'success' }, "绑定成功");
      })
      .catch(() => { })
      .then(this.loaded.bind(this))
  }
}
